package com.zhy.generator.commons.exception;

import com.google.common.collect.Lists;
import com.zhy.generator.commons.response.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * 表单验证
 */
@ControllerAdvice
@Slf4j
public class ValidatorHandlerAdvice extends ResponseEntityExceptionHandler {
    /**
     * 验证异常处理
     * @param ex
     * @param headers
     * @param status
     * @param request
     * @return
     */
    @Override
    @ResponseBody
    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        if(null != errors){
            ResultResponse resultDO = new ResultResponse();
            ObjectError error = errors.get(0);
            resultDO.setErrcode(1);
            resultDO.setMsg(error.getDefaultMessage());
            resultDO.setData(Lists.newArrayList());
            resultDO.setRequestId(System.currentTimeMillis());
            return new ResponseEntity<Object>(resultDO, status);
        }
        return null;
    }

    /**
     * 验证异常处理
     * @param ex
     * @param headers
     * @param status
     * @param request
     * @return
     */
    @Override
    @ResponseBody
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        if(null != errors){
            ResultResponse resultDO = new ResultResponse();
            ObjectError error = errors.get(0);
            resultDO.setErrcode(1);
            resultDO.setMsg(error.getDefaultMessage());
            resultDO.setData(Lists.newArrayList());
            resultDO.setRequestId(System.currentTimeMillis());
            return new ResponseEntity<Object>(resultDO, HttpStatus.OK);
        }
        return null;
    }
}
